<template>
  <div ref="chartContainer" class="bar-chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 定义props
const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({
      date: [],
      data: [], // 买入金额
      data2: []  // 卖出金额
    })
  },
  height: {
    type: String,
    default: '300px'
  }
})

// 图表容器引用
const chartContainer = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || !props.chartData.date.length) return

  chartInstance = echarts.init(chartContainer.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const dataIndex = params[0].dataIndex
        const buyAmount = props.chartData.data[dataIndex] || 0
        const sellAmount = props.chartData.data2[dataIndex] || 0
        const netAmount = props.chartData.data3[dataIndex] || 0
        
        return `${params[0].name}<br/>
                买入金额: ${buyAmount.toLocaleString()}万元<br/>
                卖出金额: ${sellAmount.toLocaleString()}万元<br/>
                净买入: ${netAmount.toLocaleString()}万元`
      },
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#409EFF',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
        fontSize: 12
      }
    },
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    xAxis: {
      type: 'category',
      show: false,
      data: props.chartData.date
    },
    yAxis: {
      type: 'value',
      show: false
    },
    series: [
      {
        name: '买入金额',
        type: 'bar',
        stack: 'total',
        data: props.chartData.data,
        itemStyle: {
          color: '#67C23A'
        },
        barWidth: '50%'
      },
      {
        name: '卖出金额',
        type: 'bar',
        stack: 'total',
        data: props.chartData.data2,
        itemStyle: {
          color: '#F56C6C'
        },
        barWidth: '50%'
      }
    ]
  }

  chartInstance.setOption(option)
}

// 更新图表
const updateChart = () => {
  if (chartInstance && props.chartData.date.length) {
    chartInstance.setOption({
      xAxis: {
        data: props.chartData.date
      },
      series: [
        {
          name: '买入金额',
          stack: 'total',
          data: props.chartData.data1
        },
        {
          name: '卖出金额',
          stack: 'total',
          data: props.chartData.data2
        }
      ]
    })
  }
}

// 监听图表数据变化
watch(() => props.chartData, () => {
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initChart()
  }, 100)
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.bar-chart-container {
  width: 100%;
  height: v-bind(height);
}
</style>